package com.josh.servlet.upload;

import java.io.File;
import java.io.IOException;
import java.util.Collection;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

@WebServlet(urlPatterns = "/UploadServlet")
@MultipartConfig
public class UploadServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public void service(HttpServletRequest request, HttpServletResponse response)
			throws IOException, ServletException {
		response.setContentType("text/html;cahrset=GBK");
		// 设置解析请求参数所用的字符集
		request.setCharacterEncoding("GBK");
		// 获取上传的文件集合
		Collection<Part> parts = request.getParts();
		// 一次性上传多个文件
		for (Part part : parts) {// 循环处理上传的文件
			// if()

			// 获取请求头，请求头的格式：form-data; name="file"; filename="snmp4j--api.zip"
			String header = part.getHeader("content-disposition");
			String rawFileName = header.substring(
					header.indexOf("filename=") + 10, header.length() - 1);

			String dd = rawFileName.substring(rawFileName.length() - 2,
					rawFileName.length());
			if (!dd.equals("dd")) {
				// 把文件写到指定路径 ; name="dd
				part.write(getServletContext().getRealPath("/") + "josh/data"
						+ File.separator + rawFileName);
			}
		}
		request.setAttribute("message", "上传完成！");
		request.getRequestDispatcher("/josh/index.jsp").forward(request,
				response);
	}

}
